// pages/components/OrgChoice/orgChoic.js
import { request } from '../../../utils/util'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    org_list: [],
    phone: "",
    current: '',
    org_id: "",
    position: 'right',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const { username, org_list } = JSON.parse(options.param)
    this.setData({
      ...this.data,
      org_list: org_list,
      phone: username,
      current: org_list[0].org_name,
      org_id: org_list[0].id
    })
  },



  /**
   * 生命周期函数--监听页面显示
   * 解决第一次登录后没选公司返回首页，自动登陆的问题
   */
  onShow: function () {
      wx.setStorageSync('choiceOrg', true)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  handleComChange({ detail }) {
    const org_id = this.getListId(detail.value)
    this.setData({
      ...this.data,
      current: detail.value,
      org_id
    });
  },
  /**
   * 传名字返回
   * @param {value} name 
   */
  getListId(name) {
    const list = this.data.org_list
    let org_id
    list.forEach(el => {
      if (el.org_name === name) {
        org_id = el.id
        return
      }
    })
    return org_id
  },

  /**
   * 登陆
   */
  login() {
    const param = {
      phone: this.data.phone,
      org: this.data.org_id
    }
    request("PUT", "/api/auth/login/", param, "", true, "进入中")
      .then(res => {
        if (res.data.code === 200) {
          
          const csrf = res.cookies[0] || ""
          const sessionId = res.cookies[1] || ""
          const a = csrf.split(";")[0]
          const b = a.split("=")[1]
          const b_name = a.split("=")[0]
          const c = sessionId.split(";")[0]
          const d = c.split("=")[1]
          const d_name = c.split("=")[0]
          if (b_name === "csrftoken") {
            wx.setStorageSync('csrf', b)
          } else {
            wx.setStorageSync('csrf', d)
          }
          wx.setStorageSync(b_name, b_name + "=" + b)
          wx.setStorageSync(d_name, d_name + "=" + d)
          wx.setStorageSync('userInfo', res.data.userInfo)
          wx.removeStorageSync('choiceOrg')
          wx.switchTab({
            url: '/pages/tabBar/search/search',
          })
        } else if (res.data.code === 422) {
          wx.showToast({
            title: res.data.message,
            icon: "none"
          })
        }
      })
  }
})